define(function () {
    return function (data) {
        var html = $(utils.getHtml('ueditor', data)).appendTo('body');
        var resizeHandler;
        html.modal('show').on('hidden.bs.modal', function (e) {
            if (resizeHandler) {
                $(window).unbind('resize', resizeHandler);
            }
            UE.delEditor('ueditor_' + data.id);
            html.remove();
        });

        var ue = UE.getEditor('ueditor_' + data.id, {
            scaleEnabled: true,
            serverUrl: data.serverUrl
        });
        ue.ready(function () {
            if (data.ready) {
                data.ready(ue);
            }

            $('.edui-editor', html).attr('style', 'width: 100%; z-index: 9000;');
            var holder = $('.edui-editor-iframeholder', html).attr('style', 'width: 100%; z-index: 9000; overflow: hidden;');
            var body = $('.modal-body', html);
            var toolbar = $('.edui-editor-toolbarbox', html);
            var footer = $('.edui-editor-bottomContainer', html);
            resizeHandler = function () {
                holder.css('height', body.height() - (toolbar.outerHeight() + footer.outerHeight()) - 2);
            }
            setTimeout(resizeHandler, 300);
            $(window).resize(resizeHandler);
        });

        $('.format-opt', html).click(function () {
            var content = $('<div>' + ue.getContent() + '</div>');
            publicApi('mirrors').then(function (mirrors) {
                $('img', content).each(function () {
                    var src = $(this).attr('src').split('?')[0];
                    for (var i in mirrors) {
                        var mirror = mirrors[i];
                        if (src.indexOf(mirror[0]) != -1) {
                            src = mirror[1] + src.split(mirror[0])[1];
                        }
                    }
                    $(this).attr('src', src);
                });
                ue.setContent(content.html());
            });
        });

        $('.save-opt', html).click(function () {
            var content = ue.getContent();
            if (data.submit) {
                data.submit(content).then(function (result) {
                    if (result.success) {
                        utils.fixedAlert('success', '保存成功');
                        html.modal('hide');
                    } else {
                        utils.fixedAlert('warning', result.message || '保存失败');
                    }
                });
            }
        });
    }
});